package com.example.demo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtils
{
  private static final ObjectMapper MAPPER = new ObjectMapper();
  
  public static String objectToJson(Object data)
  {
    try
    {
      return MAPPER.writeValueAsString(data);
    }
    catch (JsonProcessingException e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  public static <T> T jsonToPojo(String jsonData, Class<T> beanType)
  {
    try
    {
      return (T)MAPPER.readValue(jsonData, beanType);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
  
  public static <T> List<T> jsonToList(String jsonData, Class<T> beanType)
  {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, new Class[] { beanType });
    try
    {
      return (List)MAPPER.readValue(jsonData, javaType);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
}
